import { Request, Response, NextFunction } from 'express'
import {
  createComment,
  isReplyComment,
  updateComment,
  deleteComment,
  getComments,
  getCommentsTotal,
  getCommentReplies
} from './comment.service'

export const store = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { id: userId } = req.user
  const { content, postId } = req.body

  const comment = {
    content,
    user_id: userId,
    post_id: +postId
  }

  try {
    const data = await createComment(comment)
    res.send(data)
  } catch (error) {
    next(error)
  }
}

export const reply = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { commentId } = req.params
  const { id: userId } = req.user
  const { content, postId } = req.body

  const comment = {
    content,
    post_id: +postId,
    user_id: userId,
    parent_id: +commentId
  }

  try {
    const reply = await isReplyComment(+commentId)
    if (reply) {
      throw new Error('UNABLE_TO_REPLY_TO_REPLY')
    }
    const data = await createComment(comment)
    res.send(data)
  } catch (error) {
    return next(error)
  }
}

export const update = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { commentId } = req.params
  const { content } = req.body

  const comment = {
    id: +commentId,
    content
  }

  try {
    const data = await updateComment(comment)
    res.send(data)
  } catch (error) {
    next(error)
  }
}

export const destory = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { commentId } = req.params
  try {
    const data = await deleteComment(+commentId)
    res.send(data)
  } catch (error) {
    next(error)
  }
}

export const index = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const totalCount = await getCommentsTotal(req.filterParmas)
    res.header('X-Total-Count', totalCount)

    const commnents = await getComments({
      filter: req.filterParmas,
      pagination: req.pagination
    })
    res.send(commnents)
  } catch (error) {
    next(error)
  }
}

export const indexReplies = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const { commentId } = req.params

  try {
    const replies = await getCommentReplies({ commentId: +commentId })
    res.send(replies)
  } catch (error) {
    next(error)
  }
}
